package com.amos.base.util;

import com.amos.base.base.BaseDTO;
import com.amos.base.base.BaseEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.HashSet;
import java.util.Set;


/**
 * @author Amos
 * @ClassName DataU
 * @Description 数据操作类
 * @Date 2018/12/22 23:44
 * @VERSION 1.0
 **/
public class DataUtils {
    public final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * dto 转实体类
     * @param t
     * @param cls
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T extends BaseDTO, E extends BaseEntity>  E dto2Entity(T t, Class<E> cls, boolean updateAll){
        if (NullUtils.isEmpty(t)) {
            return null;
        }
        E obj = ClassUtils.newEntityInstance(cls);
        if (updateAll) {
            BeanUtils.copyProperties(t,obj);
        }else {
            BeanUtils.copyProperties(t, obj, getNullPropertyNames(t));
        }
        return obj;
    }

    /**
     * 默认是不全部转化为实体类 空值不转
     * @param t
     * @param cls
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T extends BaseDTO, E extends BaseEntity>  E dto2Entity(T t, Class<E> cls){
       return dto2Entity(t,cls,false);
    }

    /**
     * entity 转 dto
     * @param entity
     * @param cls
     * @param <T>
     * @param <E>
     * @return
     */
    public static <T extends BaseDTO, E extends BaseEntity> T entity2dto(E entity, Class<T> cls){
        if (NullUtils.isEmpty(entity)){
            return null;
        }
        T obj = ClassUtils.newDtoInstance(cls);
        BeanUtils.copyProperties(entity,obj);
        return obj;
    }

    /**
     * 过滤空值
     *
     * @param source
     * @return
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
